﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Net;
using System.Diagnostics;
using System.Windows.Forms;


namespace SharePointCustomizer
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }
        #region Local Variables
        HtmlDocument doc;
        public string projectPath = "";
        CSSViewer vwr = null;
        string oldStyle = "";
        HtmlElement elem = null;
        HtmlElement oldElem = null;

        int _elemIndex = 0;
        public bool isNew = false;

        bool cssChanged = false;

        private string typed = "";
        private bool wordMatched = false;
        private ArrayList CssFilesContent = null;
        #endregion
             
        /// <summary>
        /// Main Form Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            webBrowser.AllowNavigation = false;
            
            webBrowser.StatusTextChanged += new EventHandler(webBrowser_StatusTextChanged);
            txtUrl.KeyDown += new KeyEventHandler(txtUrl_KeyDown);
            txtUrl.Enter += new EventHandler(txtUrl_Enter);
            
            txtCSS.Controls.Add(lstAutoCom);
            txtCSS.Text = "";
         
        }
        /// <summary>
        /// txtUrl Enter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtUrl_Enter(object sender, EventArgs e)
        {
           txtUrl.SelectAll();
        }
        

        /// <summary>
        /// Fill TreeView Parent Node
        /// </summary>
        void FillTreeParentNode()
        {
            treeViewDom.Nodes.Clear();
            treeViewDom.AfterSelect += new TreeViewEventHandler(treeViewDom_AfterSelect);
            HtmlElement _body = doc.GetElementsByTagName("BODY")[0];
            TreeNode parentNode = new TreeNode(GetElementHtml(_body));

            _body.Name = "ELEM_0";
            parentNode.Tag = _body.Name;
            treeViewDom.Nodes.Add(parentNode);
            treeViewDom.SelectedNode = parentNode;

            FillTreeViewChildren(_body, parentNode);
        }
        /// <summary>
        /// Fill TreeView Children
        /// </summary>
        /// <param name="_elm"></param>
        void FillTreeViewChildren(HtmlElement _elm, TreeNode _parent)
        {
            foreach (HtmlElement _innerElm in _elm.Children)
            {
                try
                {
                    bool hidden = false;
                    if (_innerElm.Id != null)
                    {
                        if (_innerElm.Id.ToLower().Contains("viewstate"))
                        {
                            hidden = true;
                        }
                    }
                    if (GetElementHtml(_innerElm).Replace("\"", "").Replace("'", "").ToLower().Contains("type=hidden"))
                    {
                        hidden = true;
                    }
                    if (GetElementHtml(_innerElm).Replace("\"", "").Replace("'", "").ToLower().Contains("display:none"))
                    {
                        hidden = true;
                    }
                    if (_innerElm.TagName.ToLower() == "script")
                    {
                        hidden = true;
                    }
                    if (_innerElm.TagName.ToLower() == "style")
                    {
                        hidden = true;
                    }

                    if (!hidden)
                    {
                        _elemIndex += 1;
                        _innerElm.Name = "ELEM_" + _elemIndex.ToString();
                        TreeNode childNode = new TreeNode(GetElementHtml(_innerElm));
                        childNode.Tag = _innerElm.Name;
                        _parent.Nodes.Add(childNode);
                        FillTreeViewChildren(_innerElm, childNode);
                    }
                }
                catch
                {
                }
            }
        }
        /// <summary>
        /// treeViewDom AfterSelect
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void treeViewDom_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                elem = doc.All.GetElementsByName(e.Node.Tag.ToString())[0];
                HandelDocClick(elem);
            }
            catch
            {
            }
           
        }
        /// <summary>
        /// Set Clipboard Options
        /// </summary>
        void SetClipboardOptions()
        {
            if (Clipboard.ContainsText())
            {
                pasteToolStripMenuItem.Enabled = true;
                pasteToolStripMenuItem1.Enabled = true;
            }
            else
            {
                pasteToolStripMenuItem.Enabled = false;
                pasteToolStripMenuItem1.Enabled = false;
            }

        }
        /// <summary>
        /// Main Form Activated
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Activated(object sender, EventArgs e)
        {
            SetClipboardOptions();
        }
        /// <summary>
        /// webBrowser Status Text Changed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void webBrowser_StatusTextChanged(object sender, EventArgs e)
        {
            toolStripStatusLabel1.Text = webBrowser.StatusText;
        }
        /// <summary>
        /// webBrowser Navigated
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void webBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            doc = webBrowser.Document;
            doc.Click += new HtmlElementEventHandler(doc_Click);
            doc.MouseOver += new HtmlElementEventHandler(doc_MouseOver);
            doc.MouseLeave += new HtmlElementEventHandler(doc_MouseLeave);
            txtUrl.Text = webBrowser.Url.ToString();
            webBrowser.AllowNavigation = true;
            toolStripButton1.Image = SharePointCustomizer.Properties.Resources.world;
            toolStripButton1.ToolTipText = "Disable Navigation";
        }
        /// <summary>
        /// webBrowser Document Completed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            try
            {
                LoadBuiltInCssFiles();
                FillTreeParentNode();
            }
            catch
            {
            }
            
        }
        /// <summary>
        /// Style Element
        /// </summary>
        /// <param name="_elm"></param>
        void StyleElement(HtmlElement _elm)
        {
            if (_elm != oldElem)
            {
                if (_elm.Style != null)
                {
                    oldStyle = _elm.Style;
                    _elm.Style += " ; border: 2px solid magenta;";
                }
                else
                {
                    oldStyle = "";
                    _elm.Style = "border: 2px solid magenta;";
                }
            }
        }
        /// <summary>
        /// Style Element Active
        /// </summary>
        /// <param name="_elm"></param>
        void StyleElementActive(HtmlElement _elm)
        {
            if (_elm.Style != null)
            {
                oldStyle = _elm.Style;
                _elm.Style += " ; border: 2px solid green;";
            }
            else
            {
                oldStyle = "";
                _elm.Style = "border: 2px solid green;";
            }
        }
        /// <summary>
        /// doc Mouse Over
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void doc_MouseOver(object sender, HtmlElementEventArgs e)
        {
            try
            {
                elem = e.ToElement;
                StyleElement(elem);
                toolStripStatusLabel2.Text = elem.TagName;
            }
            catch
            {
            }

        }
        /// <summary>
        /// Reset border style 
        /// </summary>
        void ReseStyle(HtmlElement _elm)
        {
            if (_elm != null)
            {

                string[] rectStyle = { "BORDER-BOTTOM: magenta 2px solid", 
                                       "BORDER-TOP: magenta 2px solid", 
                                       "BORDER-RIGHT: magenta 2px solid", 
                                       "BORDER-LEFT: magenta 2px solid" };

                foreach (string txt in rectStyle)
                {
                    oldStyle = oldStyle.Replace(txt, "");
                }

                if (oldStyle != "")
                {
                    _elm.Style = oldStyle;
                }
                else
                {
                    _elm.Style = null;
                }
            }

        }
        /// <summary>
        /// Reset border style 
        /// </summary>
        void ReseStyleAtive(HtmlElement _elm)
        {
            if (_elm != null)
            {
                if (_elm != doc.ActiveElement)
                {
                    string[] rectStyle = { "BORDER-BOTTOM: green 2px solid", 
                                           "BORDER-TOP: green 2px solid", 
                                           "BORDER-RIGHT: green 2px solid", 
                                           "BORDER-LEFT: green 2px solid" };

                    foreach (string txt in rectStyle)
                    {
                        oldStyle = oldStyle.Replace(txt, "");
                    }

                    if (oldStyle != "")
                    {
                        _elm.Style = oldStyle;
                    }
                    else
                    {
                        _elm.Style = null;
                    }
                }
            }
        }

        /// <summary>
        /// doc Mouse Leave
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void doc_MouseLeave(object sender, HtmlElementEventArgs e)
        {
            try
            {
                ReseStyle(elem);
            }
            catch
            {
            }
        }

        void HandelDocClick(HtmlElement _elm)
        {
            try
            {
                ReseStyle(_elm);
                ReseStyleAtive(oldElem);
                
                lblShowID.Text = _elm.Id;
                propertyGrid.SelectedObject = _elm;
               
                oldElem = _elm;
                StyleElementActive(_elm);
                pnlClass.Controls.Clear();
                string cls = GetClassName(_elm);
                string[] clsVars = cls.Split(' ');
                foreach (string _txt in clsVars)
                {
                    if (_txt != "" && _txt != null)
                    {
                        LinkLabel lnkLbl = new LinkLabel();
                        lnkLbl.Text = _txt;
                        lnkLbl.Click += new EventHandler(lnkLbl_Click);
                        lnkLbl.Size = lnkLbl.PreferredSize;
                        pnlClass.Controls.Add(lnkLbl);
                    }
                }
            }
            catch
            {
                
            }
        }
        /// <summary>
        /// Search Tree
        /// </summary>
        /// <param name="nodes"></param>
        /// <param name="searchtext"></param>
        /// <returns></returns>
        public TreeNode SearchTree(TreeNodeCollection nodes, string searchtext)
        {
            TreeNode result = null;

            foreach (TreeNode node in nodes)
            {
                if (node.Tag as string == searchtext)
                {
                    result = node;
                }
                else
                {
                    result = SearchTree(node.Nodes, searchtext);
                }
                if (result != null)
                {
                    break;
                }
            }
            return result;
        }

        /// <summary>
        /// doc Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void doc_Click(object sender, HtmlElementEventArgs e)
        {
            try
            {
                HandelDocClick(elem);
                treeViewDom.Focus();
                treeViewDom.SelectedNode = SearchTree(treeViewDom.Nodes, elem.Name);
                treeViewDom.SelectedNode.Expand();
            }
            catch
            {
            }
        }
        /// <summary>
        /// lnkLbl Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void lnkLbl_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            LinkLabel clsLnk = (LinkLabel)sender;
            vwr = new CSSViewer();
            bool found = false;
            foreach (string _item in CssFilesContent)
            {
                if (_item.ToLower().Contains("." + clsLnk.Text.ToLower()))
                {
                    vwr.strCssAll = _item;
                    vwr.strHighlight = clsLnk.Text;
                    try
                    {
                        vwr.Show(this);
                    }
                    catch
                    {
                    }
                    
                    found = true;
                }
            }
            if (!found)
            {
                if ( webBrowser.DocumentText.ToLower().Contains("." + clsLnk.Text.ToLower()))
                {
                    vwr.strCssAll = webBrowser.DocumentText;
                    vwr.strHighlight = clsLnk.Text;
                    try
                    {
                        vwr.Show(this);
                    }
                    catch
                    {
                    }
                }
            }
            Cursor.Current = Cursors.Arrow;
        }

        /// <summary>
        /// Adjust Html
        /// </summary>
        /// <param name="_html"></param>
        /// <returns></returns>
        string RefineHtml(string _html)
        {
            string _outStr = _html.Trim()
                             .Replace("\n", "")
                             .Replace("\r", "")
                             .Replace("\t", " ")
                             .Replace(" =", "=")
                             .Replace("= ", "=");
            return _outStr;
        }
        /// <summary>
        /// Get Class Name from Html Element
        /// </summary>
        /// <param name="_elem"></param>
        /// <returns></returns>
        string GetClassName(HtmlElement _elem)
        {

            string buffer = "";
            buffer = GetElementHtml(_elem).Replace("'", "\"");
           
            string[] sep = { "class=" };
            string[] strVars = buffer.Split(sep, StringSplitOptions.RemoveEmptyEntries);
            if (strVars[1].StartsWith("\""))
            {
                strVars = strVars[1].Split('"');
                return strVars[1];
            }
            else
            {
                strVars = strVars[1].Split(' ');
                strVars = strVars[0].Split('>');
                return strVars[0].Replace("\"", "");
            }
        }
        /// <summary>
        /// Gets Element Html
        /// </summary>
        /// <returns></returns>
        string GetElementHtml(HtmlElement _elem)
        {
            string innerHTML = "";
            string buffer = "";
            if (_elem.InnerHtml != null)
            {
                innerHTML = RefineHtml(_elem.InnerHtml.ToLower());

                buffer = RefineHtml(_elem.OuterHtml.ToLower());

                buffer = buffer.Replace(innerHTML, "");
            }
            else
            {
                buffer = RefineHtml(_elem.OuterHtml.ToLower());
            }
            buffer = buffer.Replace("</" + _elem.TagName.ToLower()+ ">","");
            return buffer;
        }
        /// <summary>
        /// txtUrl KeyDown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtUrl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                GetPage();
            }
        }
        /// <summary>
        /// toolStripButton1 Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (toolStripButton1.Checked)
            {
                webBrowser.AllowNavigation = false;
                toolStripButton1.Image = SharePointCustomizer.Properties.Resources.world_delete;
                toolStripButton1.ToolTipText = "Enable Navigation";
                toolStripButton1.Checked = true;
                disableNavigationToolStripMenuItem.Checked = true;

            }
            else
            {
                webBrowser.AllowNavigation = true;
                toolStripButton1.Image = SharePointCustomizer.Properties.Resources.world;
                toolStripButton1.ToolTipText = "Disable Navigation";
                toolStripButton1.Checked = false;
                disableNavigationToolStripMenuItem.Checked = false;

            }
            Application.DoEvents();
            
        }
        /// <summary>
        /// Load Css Files
        /// </summary>
        private void InitiateCss()
        {
            if (projectPath != "")
            {
                comboBoxStyle.Items.Clear();
                string cssDir = projectPath + "\\css";
                string imgDir = projectPath + "\\images";
                if (!Directory.Exists(cssDir))
                {
                    Directory.CreateDirectory(cssDir);
                }
                if (!Directory.Exists(imgDir))
                {
                    Directory.CreateDirectory(imgDir);
                }
                
                string[] cssFiles = Directory.GetFiles(cssDir);
                foreach (string _file in cssFiles)
                {
                    if (!_file.ToLower().EndsWith("-tmp.css"))
                    {
                        comboBoxStyle.Items.Add(_file);
                        ApplyCss(_file);
                    }
                }
                if (comboBoxStyle.Items.Count > 0)
                {
                    comboBoxStyle.SelectedIndex = 0;
                }
            }
        }
        /// <summary>
        /// Get Domain Name from Utl
        /// </summary>
        /// <returns></returns>
        string GetDomainName(string Url)
        {
            string[] vars = Url.Split('/');
            return vars[0] + "//" + vars[1] + vars[2];
        }

        /// <summary>
        /// Load Built-in Css Files
        /// </summary>
        private void LoadBuiltInCssFiles()
        {
            string strAll = "";
            string strCssHref = "";
            CssFilesContent = new ArrayList();
            string serverName = GetDomainName(webBrowser.Url.ToString());
            string Url = "";
            foreach (HtmlElement _elm in doc.GetElementsByTagName("LINK"))
            {
                try
                {
                    strCssHref = _elm.GetAttribute("href");
                    if (strCssHref.Contains(".css"))
                    {
                        Url = serverName + strCssHref.Split('?')[0];

                        Uri uri = new Uri(Url);
                        WebRequest req = WebRequest.Create(uri);

                        req.PreAuthenticate = true;

                        req.Credentials = System.Net.CredentialCache.DefaultCredentials;

                        WebResponse resp = req.GetResponse();

                        Stream stream = resp.GetResponseStream();

                        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

                        StreamReader sr = new StreamReader(stream, encode);

                        strAll = sr.ReadToEnd();

                        sr.Close();
                        stream.Close();
                        resp.Close();

                        sr.Dispose();
                        stream.Dispose();

                        CssFilesContent.Add(strAll);
                    }
                }
                catch
                {
                }
            }
        }
        /// <summary>
        /// Reload Css
        /// </summary>
        private void ReLoadCss()
        {
            if (projectPath != "")
            {
                string cssDir = projectPath + "\\css";
                string[] cssFiles = Directory.GetFiles(cssDir);
                foreach (string _file in cssFiles)
                {
                    if (!_file.ToLower().EndsWith("-tmp.css"))
                    {
                       ApplyCss(_file);
                    }
                }
                
            }
        }
        /// <summary>
        /// Loading internet site
        /// </summary>
        private void GetPage()
        {
            try
            {
                webBrowser.AllowNavigation = true;
                toolStripButton1.Checked = false;
                Application.DoEvents();
                if (!txtUrl.Text.StartsWith("http://") && 
                    !txtUrl.Text.StartsWith("https://") &&
                    !txtUrl.Text.StartsWith("about:") &&
                    !txtUrl.Text.StartsWith("file:///") &&
                    !txtUrl.Text.StartsWith("ftp://")&&
                    !txtUrl.Text.StartsWith("sop://")&&
                    !txtUrl.Text.StartsWith("mailto:"))
                {
                    txtUrl.Text = "http://" + txtUrl.Text;
                }
                webBrowser.Url = new Uri(txtUrl.Text);
                        
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK);
            }
        }
        /// <summary>
        /// btnGo Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGo_Click(object sender, EventArgs e)
        {
            GetPage();
        }
        /// <summary>
        /// Apply Css
        /// </summary>
        /// <param name="_file"></param>
        public void ApplyCss(string _file)
        {
            try
            {
                HtmlElement elmt = doc.CreateElement("LINK");
                elmt.SetAttribute("rel", "stylesheet");
                elmt.SetAttribute("type", "text/css");
                elmt.SetAttribute("href", _file);
                doc.GetElementsByTagName("HEAD")[0].InsertAdjacentElement(HtmlElementInsertionOrientation.BeforeEnd, elmt);
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// saveHTMLToolStripMenuItem Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void saveHTMLToolStripMenuItem_Click(object sender, EventArgs e)
        {
            webBrowser.ShowSaveAsDialog();
        }
        /// <summary>
        /// cSSFileToolStripMenuItem1 Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cSSFileToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            AddCss sccWindow = new AddCss();
            sccWindow.projectPath = this.projectPath;
            sccWindow.ShowDialog(this);
            ApplyCss(comboBoxStyle.SelectedText);
        }
        /// <summary>
        /// projectToolStripMenuItem Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void projectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewProject projWindow = new NewProject();
            projWindow.ShowDialog(this);

        }
        /// <summary>
        /// cSSFileToolStripMenuItem Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cSSFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
           
            folderBrowserDialog.ShowDialog(this);
            
            if (folderBrowserDialog.SelectedPath != null)
            {
                this.projectPath = folderBrowserDialog.SelectedPath;
                InitiateCss();
            }

        }
        /// <summary>
        /// Write Css File Content
        /// </summary>
        void WriteCssFileContent()
        {
            string fileName = comboBoxStyle.Text;
            if (fileName.Trim() != "")
            {
                StreamWriter wrtr = new StreamWriter(fileName);
                wrtr.Write(txtCSS.Text);
                wrtr.Close();
                File.Copy(fileName, fileName.ToLower().Replace(".css", "-tmp.css"), true);
            }
            else
            {
                MessageBox.Show("You have to add CSS file.","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
       }

        /// <summary>
        /// Load Css Files
        /// </summary>
        private void LoadCss()
        {
            if (projectPath != "" && projectPath != null)
            {
                bool itemsFound = false;

                HtmlElementCollection _elms = doc.GetElementsByTagName("LINK");
                
                foreach (HtmlElement _elm in _elms)
                {
                    if (_elm.GetAttribute("href").ToLower() == comboBoxStyle.Text.ToLower())
                    {
                        _elm.SetAttribute("href", comboBoxStyle.Text.Replace(".css", "-tmp.css"));
                        itemsFound = true;
                    }
                    else if (_elm.GetAttribute("href").ToLower() == comboBoxStyle.Text.ToLower().Replace(".css", "-tmp.css"))
                    {
                        _elm.SetAttribute("href", comboBoxStyle.Text.Replace(".css", "-tmp.css"));
                        itemsFound = true;
                    }
                }
                if (!itemsFound)
                {
                    ReLoadCss();
                }
             }
        }
        /// <summary>
        /// btnApplyOnCss Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnApplyOnCss_Click(object sender, EventArgs e)
        {
            if (projectPath != "" && projectPath != null)
            {
                WriteCssFileContent();
                LoadCss();

                cssChanged = false;
            }
            else
            {
                MessageBox.Show("No Project Loaded.");
            }
           
        }
        /// <summary>
        /// toolStripButton2 Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            backToolStripMenuItem_Click(sender, e);
        }
        /// <summary>
        /// backToolStripMenuItem Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backToolStripMenuItem_Click(object sender, EventArgs e)
        {
            webBrowser.GoBack();
        }
        /// <summary>
        /// forwardToolStripMenuItem Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void forwardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            webBrowser.GoForward();
        }
        /// <summary>
        /// toolStripButton3 Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            forwardToolStripMenuItem_Click(sender, e);
        }
        /// <summary>
        /// stopToolStripMenuItem Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void stopToolStripMenuItem_Click(object sender, EventArgs e)
        {
            webBrowser.Stop();
        }
        /// <summary>
        /// toolStripButton5 Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            stopToolStripMenuItem_Click(sender, e);
        }
        /// <summary>
        /// refreshToolStripMenuItem Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            webBrowser.Refresh();
            if (projectPath != "" && projectPath != null)
            {
               ReLoadCss();
            }
        }
        /// <summary>
        /// toolStripButton4 Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            refreshToolStripMenuItem_Click(sender, e);
        }
        /// <summary>
        /// webBrowser ProgressChanged
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void webBrowser_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
        {
            ToolStripProgressBar pBar;
            if (statusStrip.Items["ProgressBar"] == null)
            {
                pBar = new ToolStripProgressBar("ProgressBar");
                statusStrip.Items.Add(pBar);
            }
            else
            {
                pBar = (ToolStripProgressBar)statusStrip.Items["ProgressBar"];
            }
            pBar.Value = (int)e.CurrentProgress;
            if (pBar.Value == (int)e.MaximumProgress)
            {
                pBar.Dispose();
            }
        }
        /// <summary>
        /// btnOverride Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOverride_Click(object sender, EventArgs e)
        {
            
            if (pnlClass.Controls.Count>0)
            {                
                foreach (Control _lnk in pnlClass.Controls)
                {
                    txtCSS.AppendText("\n" + "." + _lnk.Text + "\n{\r\n}");
                }
            }
        }
        /// <summary>
        /// btnOverrideID Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOverrideID_Click(object sender, EventArgs e)
        {
            if (lblShowID.Text != "")
            {
                txtCSS.AppendText("\n" + "#" + lblShowID.Text + "\n{\r\n}");
            }
        }
        /// <summary>
        /// txtCSS KeyDown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCSS_KeyDown(object sender, KeyEventArgs e)
        {
            // Keep track of the current character, used
            // for tracking whether to hide the list of members,
            // when the delete button is pressed
            int i = this.txtCSS.SelectionStart;
            string currentChar = "";

            if (i > 0)
            {
                currentChar = this.txtCSS.Text.Substring(i - 1, 1);
            }

            if ((this.txtCSS.GetFirstCharIndexOfCurrentLine() == txtCSS.SelectionStart 
                        && (e.KeyCode == Keys.Space || e.KeyCode == Keys.Tab))
                        || (e.KeyCode == Keys.Enter && (currentChar == "{") || (currentChar == ";"))
                        || ((e.KeyCode == Keys.Space || e.KeyCode == Keys.Tab) 
                        && (currentChar == ";" || currentChar == "{")))
            {
                if (!this.lstAutoCom.Visible || e.KeyCode == Keys.Space || e.KeyCode == Keys.Tab)
                {
                    // Display the member listview if there are
                    // items in it
                    this.lstAutoCom.SelectedIndex = 0;
                    this.lstAutoCom.ClearSelected();
                                        
                    // Find the position of the caret
                    Point point = this.txtCSS.GetPositionFromCharIndex(txtCSS.SelectionStart);
                    point.Y += (int)Math.Ceiling(this.txtCSS.Font.GetHeight()) + 2;
                    point.X += 2; // for Courier, may need a better method

                    int criticalX = this.txtCSS.Width - this.lstAutoCom.Width - 25;
                    int criticalY = this.txtCSS.Height - this.lstAutoCom.Height - 10;
                    if (point.X > criticalX)
                    {
                        point.X = criticalX;
                    }
                    if (point.Y > criticalY)
                    {
                        point.Y = criticalY;
                    }
                    this.lstAutoCom.Location = point;
                    this.lstAutoCom.BringToFront();
                    this.lstAutoCom.Show();

                }
                else
                {
                    this.lstAutoCom.Hide();
                    typed = "";
                }
            }
            else if (e.KeyCode == Keys.Back)
            {
                // Delete key - hides the member list if the character
                // being deleted is a dot

                if (typed.Length > 0)
                {
                    typed = typed.Substring(0, typed.Length - 1);
                }
                else
                {

                    this.lstAutoCom.Hide();
                    typed = "";
                }
            }
            else if (e.KeyCode == Keys.Up)
            {
                // The up key moves up our member list, if
                // the list is visible

                if (this.lstAutoCom.Visible)
                {
                    this.wordMatched = true;
                    if (this.lstAutoCom.SelectedIndex > 0)
                        this.lstAutoCom.SelectedIndex--;

                    e.Handled = true;
                }
            }
            else if (e.KeyCode == Keys.Down)
            {
                // The up key moves down our member list, if
                // the list is visible

                if (this.lstAutoCom.Visible)
                {
                    this.wordMatched = true;
                    if (this.lstAutoCom.SelectedIndex < this.lstAutoCom.Items.Count - 1)
                        this.lstAutoCom.SelectedIndex++;

                    e.Handled = true;
                }
            }
            
            else if (e.KeyValue < 48 
                        || (e.KeyValue >= 58 && e.KeyValue <= 64) 
                        || (e.KeyValue >= 91 && e.KeyValue <= 96) 
                        || e.KeyValue > 122 && e.KeyCode != Keys.OemMinus)
            {
                // Check for any non alphanumerical key, hiding
                // member list box if it's visible.

                if (this.lstAutoCom.Visible)
                {
                    // Check for keys for autofilling (return,tab,space)
                    // and autocomplete the richtextbox when they're pressed.
                    if (e.KeyCode == Keys.Return || e.KeyCode == Keys.Tab || e.KeyCode == Keys.Space)
                    {
                        // Autocomplete
                        this.selectItem();

                        this.typed = "";
                        this.wordMatched = false;
                        e.Handled = true;
                    }

                    // Hide the member list view
                    this.lstAutoCom.Hide();
                }
            }
            else
            {
                // Letter or number typed, search for it in the listview
                if (this.lstAutoCom.Visible)
                {
                    char val;
                    if (e.KeyCode == Keys.OemMinus)
                    {
                        val = '-';
                    }
                    else
                    {
                        val = (char)e.KeyValue;
                    }

                    this.typed += val;

                    this.wordMatched = false;

                    // Loop through all the items in the listview, looking
                    // for one that starts with the letters typed
                    for (i = 0; i < this.lstAutoCom.Items.Count; i++)
                    {
                        if (this.lstAutoCom.Items[i].ToString().ToLower().StartsWith(this.typed.ToLower()))
                        {
                            this.wordMatched = true;
                            this.lstAutoCom.SelectedIndex = i;
                            break;
                        }
                    }
                }
                else
                {
                    this.typed = "";
                }
            }
        }

        /// <summary>
        /// Searches backwards from the current caret position, until
        /// a space or newline is found.
        /// </summary>
        /// <returns>The previous word from the carret position</returns>
        private string getLastWord()
        {
            string word = "";

            int pos = this.txtCSS.SelectionStart;
            if (pos > 1)
            {
                string tmp = "";
                char f = new char();
                while (f != ' ' && f != 10 && pos > 0)
                {
                    pos--;
                    tmp = this.txtCSS.Text.Substring(pos, 1);
                    f = (char)tmp[0];
                    word += f;
                }
                char[] ca = word.ToCharArray();
                Array.Reverse(ca);
                word = new String(ca);
            }
            return word.Trim();
        }
        /// <summary>
        /// txtCSS MouseDown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCSS_MouseDown(object sender, MouseEventArgs e)
        {
            this.lstAutoCom.Hide();
        }
        /// <summary>
        /// lstAutoCom KeyDown
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstAutoCom_KeyDown(object sender, KeyEventArgs e)
        {
            this.txtCSS.Focus();
        }
        /// <summary>
        /// lstAutoCom DoubleClick
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstAutoCom_DoubleClick(object sender, EventArgs e)
        {
            // Item double clicked, select it
            if (this.lstAutoCom.SelectedItems.Count == 1)
            {
                this.wordMatched = true;
                this.selectItem();
                this.lstAutoCom.Hide();
                this.txtCSS.Focus();
                this.wordMatched = false;
            }
        }
        /// <summary>
        /// lstAutoCom SelectedIndexChanged
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lstAutoCom_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.txtCSS.Focus();
        }
        /// <summary>
        /// textBoxTooltip Enter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxTooltip_Enter(object sender, EventArgs e)
        {
            this.txtCSS.Focus();
        }

        /// <summary>
        /// Autofills the selected item in the member listbox, by
        /// taking everything before and after the "." in the richtextbox,
        /// and appending the word in the middle.
        /// </summary>
        private void selectItem()
        {
            if (this.wordMatched && this.lstAutoCom.SelectedItem!=null)
            {
                txtCSS.Select(txtCSS.SelectionStart - typed.Length, typed.Length);
                this.txtCSS.SelectedText = this.lstAutoCom.SelectedItem.ToString();
            }
        }
        /// <summary>
        /// colorToolStripMenuItem Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void colorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (colorDialog.ShowDialog() != DialogResult.Cancel)
            {
                txtCSS.SelectedText = ColorTranslator.ToHtml(colorDialog.Color);
            }
        }
        /// <summary>
        /// toolStripButton6 Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            colorToolStripMenuItem_Click(sender, e);
        }
        /// <summary>
        /// btnAddImage Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAddImage_Click(object sender, EventArgs e)
        {
            openFileDialog.Filter = "Bitmap Files (*.bmp)|*.bmp|JPEG Files (*.jpg,*.jpeg)|*.jpg|GIF Files (*.gif)|*.gif|PNG Files (*.png)|*.png";
            openFileDialog.ShowDialog();
        }
        /// <summary>
        /// openFileDialog FileOk
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openFileDialog_FileOk(object sender, CancelEventArgs e)
        {
            if (!e.Cancel && projectPath != null && projectPath != "")
            {
                if (!Directory.Exists(projectPath + "\\images\\"))
                {
                    Directory.CreateDirectory(projectPath + "\\images\\");
                }
                File.Copy(openFileDialog.FileName, projectPath + "\\images\\" + openFileDialog.SafeFileName,true);

                txtCSS.SelectedText = "url(../images/" + openFileDialog.SafeFileName + ")";
            }
            if (projectPath == "" || projectPath ==null)
            {
                MessageBox.Show("No Project Loaded.");
            }
        }
        /// <summary>
        /// copyToolStripMenuItem Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (txtCSS.Focused && txtCSS.SelectedText!="")
            {
                txtCSS.Copy();
            }
            else if (webBrowser.Focused)
            {
                webBrowser.Document.ExecCommand("Copy",false,null);
            }
            else if (propertyGrid.Focused )
            {
                Clipboard.SetText(propertyGrid.SelectedGridItem.Value.ToString());
            }
            else if (txtUrl.Focused && txtUrl.SelectedText!="")
            {
                txtUrl.Copy();
            }
            else if (lblShowID.Focused && lblShowID.SelectedText != "")
            {
                lblShowID.Copy();
            }
            else if (comboBoxStyle.Focused && comboBoxStyle.SelectedText!="")
            {
                Clipboard.SetText(comboBoxStyle.SelectedText);
            }

            SetClipboardOptions();
        }
        /// <summary>
        /// pasteToolStripMenuItem_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (txtCSS.Focused && Clipboard.ContainsText())
            {
                txtCSS.Paste();
            }
            else if (webBrowser.Focused && Clipboard.ContainsText())
            {
                webBrowser.Document.ExecCommand("Paste", false, null);
            }
            else if (txtUrl.Focused && Clipboard.ContainsText())
            {
                txtUrl.Paste();
            }
            
        }
        /// <summary>
        /// cutCSSToolStripMenuItem_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cutCSSToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (txtCSS.Focused && txtCSS.SelectedText != "")
            {
                txtCSS.Cut();
            }
            else if (webBrowser.Focused)
            {
                webBrowser.Document.ExecCommand("Cut", false, null);
            }
            
            else if (txtUrl.Focused && txtUrl.SelectedText != "")
            {
                txtCSS.Cut();
            }
            else if (lblShowID.Focused && lblShowID.SelectedText != "")
            {
                txtCSS.Cut();
            }
            SetClipboardOptions();
       }
        /// <summary>
        /// selectAllToolStripMenuItem_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (txtCSS.Focused )
            {
                txtCSS.SelectAll();
            }
            else if (webBrowser.Focused)
            {
                webBrowser.Document.ExecCommand("SelectAll", false, null);
            }

            else if (txtUrl.Focused )
            {
                txtUrl.SelectAll();
            }
            else if (lblShowID.Focused )
            {
                lblShowID.SelectAll();
            }
        }
        /// <summary>
        /// cutToolStripMenuItem_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cutCSSToolStripMenuItem_Click(sender, e);
        }
        /// <summary>
        /// copyToolStripMenuItem1_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void copyToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            copyToolStripMenuItem_Click(sender, e);
        }
        /// <summary>
        /// pasteToolStripMenuItem1_Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pasteToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            pasteToolStripMenuItem_Click(sender, e);
        }
        
        /// <summary>
        /// Open Explorer
        /// </summary>
        /// <param name="f"></param>
        void OpenExplorer(string arg)
        {
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "EXPLORER.EXE";
            startInfo.Arguments = arg;
            Process.Start(startInfo);
        }

        void SetCssFileContent()
        {
            StreamReader strRead = File.OpenText(comboBoxStyle.Text);
            txtCSS.Text = strRead.ReadToEnd();
            strRead.Close();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxStyle.Text != "" && comboBoxStyle.Text != null && !isNew)
            {
                if (cssChanged)
                {
                    if (MessageBox.Show("Are you sure you applied your custom css.", "Confirmation", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        SetCssFileContent();
                    }
                }
                else
                {
                    SetCssFileContent();
                }
            }
        }
        /// <summary>
        /// txtCSS TextChanged
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtCSS_TextChanged(object sender, EventArgs e)
        {
            if (projectPath != "" && projectPath!=null)
            {
                cssChanged = true;
            }
            
        }
        void GetPackage( string destPath)
        {
            string cssDir = projectPath + "\\css";
            string imgDir = projectPath + "\\images";
            string[] cssFiles = Directory.GetFiles(cssDir);
            string[] imgFiles = Directory.GetFiles(imgDir);
            Directory.CreateDirectory(destPath + "\\css");
            string safeFileName = ""; 
            foreach (string _file in cssFiles)
            {
                if (!_file.ToLower().EndsWith("-tmp.css"))
                {
                    string[] pathVars = _file.Split('\\');
                    safeFileName = pathVars[pathVars.Length-1];
                    File.Copy(_file, destPath + "\\css\\" + safeFileName, true);
                }
            }
            Directory.CreateDirectory(destPath + "\\images");
            foreach (string _file in imgFiles)
            {
                string[] pathVars = _file.Split('\\');
                safeFileName = pathVars[pathVars.Length - 1];
                File.Copy(_file, destPath + "\\images\\" + safeFileName, true);
            }
        }
        /// <summary>
        /// export Theme Tool Strip Menu Item Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void exportThemeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (projectPath != null && projectPath != "")
            {
                folderBrowserDialogExport.ShowDialog();
                if (folderBrowserDialogExport.SelectedPath != null)
                {
                    GetPackage(folderBrowserDialogExport.SelectedPath);
                    MessageBox.Show("Project files exported successfully.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show("No Project Loaded.");
            }

        }
        /// <summary>
        /// open Project Folder
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openProjectFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (projectPath != "" && projectPath != null)
            {
                OpenExplorer(projectPath);
            }
            else
            {
                MessageBox.Show("No Project Loaded.");
            }
            
        }
        /// <summary>
        /// btnInsertImage Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnInsertImage_Click(object sender, EventArgs e)
        {
            if (projectPath != null && projectPath != "")
            {
                if (!Directory.Exists(projectPath + "\\images\\"))
                {
                    Directory.CreateDirectory(projectPath + "\\images\\");
                }
                openFileDialogAddImage.InitialDirectory = projectPath + "\\images\\";
                openFileDialogAddImage.Filter = "Bitmap Files (*.bmp)|*.bmp|JPEG Files (*.jpg,*.jpeg)|*.jpg|GIF Files (*.gif)|*.gif|PNG Files (*.png)|*.png";
                openFileDialogAddImage.ShowDialog();
            }

            if (projectPath == "" || projectPath == null)
            {
                MessageBox.Show("No Project Loaded.");
            }
         }
        /// <summary>
        /// openFileDialogAddImage FileOk
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void openFileDialogAddImage_FileOk(object sender, CancelEventArgs e)
        {
            if (!e.Cancel)
            {
                txtCSS.SelectedText = "url(../images/" + openFileDialogAddImage.SafeFileName + ")";
            }
            
        }
        /// <summary>
        /// About Tool StripMenuItem Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox about = new AboutBox();
            about.ShowDialog(this);

        }
        /// <summary>
        /// disableNavigationToolStripMenuItem Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void disableNavigationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (disableNavigationToolStripMenuItem.Checked)
            {
                webBrowser.AllowNavigation = false;
                toolStripButton1.Image = SharePointCustomizer.Properties.Resources.world_delete;
                toolStripButton1.ToolTipText = "Enable Navigation";
                toolStripButton1.Checked = true;
          
            }
            else
            {
                webBrowser.AllowNavigation = true;
                toolStripButton1.Image = SharePointCustomizer.Properties.Resources.world;
                toolStripButton1.ToolTipText = "Disable Navigation";
                toolStripButton1.Checked = false;
               
            }
            Application.DoEvents();
        }
    }
       
}
